package com.quiz.bis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.quiz.bis.domain.bo.MemberApproveBo;
import com.quiz.bis.domain.bo.MemberInviteBo;
import com.quiz.bis.domain.model.ExamGroup;
import com.quiz.bis.domain.model.ExamGroupInviteRecord;
import com.quiz.bis.domain.model.ExamGroupMember;
import com.quiz.bis.domain.vo.ExamMemberVo;
import com.quiz.bis.domain.vo.PendingMemberVo;
import com.quiz.bis.mapper.ExamGroupInviteRecordMapper;
import com.quiz.bis.mapper.ExamGroupMapper;
import com.quiz.bis.mapper.ExamGroupMemberMapper;
import com.quiz.bis.service.IExamGroupMemberService;
import com.quiz.common.core.domain.R;
import com.quiz.common.core.domain.entity.SysUser;
import com.quiz.common.mybatis.core.page.PageQuery;
import com.quiz.common.mybatis.core.page.TableDataInfo;
import com.quiz.common.mybatis.core.query.PlusWrappers;
import com.quiz.common.utils.SecurityUtils;
import com.quiz.system.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * 考试组成员服务实现类
 */
@Service
@RequiredArgsConstructor
public class ExamGroupMemberServiceImpl implements IExamGroupMemberService {
    private final ExamGroupMemberMapper memberMapper;
    private final ExamGroupInviteRecordMapper inviteRecordMapper;
    private final SysUserMapper userMapper;
    private final ExamGroupMapper groupMapper;

    @Override
    public TableDataInfo<PendingMemberVo> getPendingMembers(Long groupId, PageQuery pageQuery) {
        Page<PendingMemberVo> page = memberMapper.selectPendingMembers(
                pageQuery.build(),
                groupId
        );
        return TableDataInfo.build(page);
    }

    @Override
    @Transactional
    public R<Void> approveMember(MemberApproveBo bo) {
        Long userId = SecurityUtils.getUserId();
        ExamGroupMember member = memberMapper.selectById(bo.getMemberId());

        // 验证权限
        if (!isGroupOwner(member.getExamGroupId(), userId)) {
            return R.fail("只有主要负责人可以审核");
        }

        if (bo.getApproved()) {
            // 通过申请
            member.setApproveStatus(1);
            member.setUpdateBy(String.valueOf(userId));
            memberMapper.updateById(member);

            // 发送通知
//            sendNotification(member.getUserId(), "申请已通过");
        } else {
            // 拒绝申请
            memberMapper.update(
                    PlusWrappers.lambdaUpdate(ExamGroupMember.class)
                            .eq(ExamGroupMember::getId, bo.getMemberId())
                            .eq(ExamGroupMember::getExamGroupId, member.getExamGroupId())
                            .set(ExamGroupMember::getApproveStatus, 2)
            );
            inviteRecordMapper.update(
                    PlusWrappers.lambdaUpdate(ExamGroupInviteRecord.class)
                            .eq(ExamGroupInviteRecord::getInviteeId, member.getUserId())
                            .eq(ExamGroupInviteRecord::getExamGroupId, member.getExamGroupId())
                            .set(ExamGroupInviteRecord::getStatus, 2)
            );
//            sendNotification(member.getUserId(), "申请被拒绝");
        }

        return R.ok();
    }

    @Override
    @Transactional
    public R<Void> inviteMember(MemberInviteBo bo) {
        Long userId = SecurityUtils.getUserId();

        // 查找用户
        SysUser invitee = userMapper.selectUserByUserName(bo.getUserAccount());
        if (invitee == null) {
            return R.fail("用户不存在");
        }

        // 检查是否已是成员
        boolean exists = memberMapper.exists(
                new LambdaQueryWrapper<ExamGroupMember>()
                        .eq(ExamGroupMember::getExamGroupId, bo.getGroupId())
                        .eq(ExamGroupMember::getUserId, invitee.getUserId())
        );

        if (exists) {
            return R.fail("该用户已是成员");
        }

        // 创建成员记录
        ExamGroupMember member = new ExamGroupMember();
        member.setExamGroupId(bo.getGroupId());
        member.setUserId(invitee.getUserId());
        member.setRole(bo.getRole());
        member.setApproveStatus(bo.isNeedConfirm() ? 0 : 1); // 是否需要审核
        member.setJoinSource(2); // 邀请加入
        member.setCreateBy(String.valueOf(userId));
        memberMapper.insert(member);

        // 发送通知
//        sendNotification(invitee.getUserId(), "您已被邀请加入考试组");

        return R.ok();
    }

    @Override
    @Transactional
    public R<Void> removeMember(Long memberId) {
        ExamGroupMember member = memberMapper.selectById(memberId);
        if (member == null) {
            return R.fail("成员不存在");
        }

        // 不能移除自己
        if (member.getUserId().equals(SecurityUtils.getUserId())) {
            return R.fail("不能移除自己");
        }

        // 主要负责人不能移除
        if (member.getRole() == 1) {
            return R.fail("不能移除主要负责人");
        }

        memberMapper.deleteById(memberId);
        return R.ok();
    }




    @Override
    public TableDataInfo<ExamMemberVo> getStuMembers(Long groupId, String keyword, PageQuery pageQuery){
        Page<ExamMemberVo> examMemberVos = memberMapper.selectStuMembers(pageQuery.build(), groupId, keyword);
        return TableDataInfo.build(examMemberVos);
    }



    private boolean isGroupOwner(Long groupId, Long userId) {
        ExamGroup group = groupMapper.selectById(groupId);
        return group != null && group.getMainOwnerId().equals(userId);
    }
}
